<!-- 团购管理 -->
<template>
  <div class="box_container">
    <!-- 输入框 -->
    <div class="box_input">
      <el-input v-model="pageinfo.spuName" placeholder="请输入商品名称"></el-input>
      <el-input v-model="pageinfo.id" placeholder="请输入团购ID"></el-input>
      <el-select v-model="pageinfo.status" placeholder="请选择商品状态">
        <el-option v-for="item in adStatusMap" :key="item.value" :label="item.name" :value="item.value">
        </el-option>
      </el-select>
      <el-button icon="el-icon-search" type="primary" @click="onSeek">查找</el-button>
      <el-button icon="el-icon-plus" type="primary" @click="addAdmin">添加</el-button>
    </div>
    <!-- 团购管理列表 -->
    <div class="box_table">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="类目ID" width="120px">{{scope.row.categoryId}}</el-descriptions-item>
              <el-descriptions-item label="商品sku属性">
                <el-table :data='scope.row.groupShopSkuDTOList' :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}" border>
                  <el-table-column label="Skuid" prop="id">
                  </el-table-column>
                  <el-table-column label="规格标题" prop="title">
                  </el-table-column>
                  <el-table-column label="团购价格（元）" prop="skuGroupShopPrice">
                  </el-table-column>
                  <el-table-column label="库存" prop="stock">
                    <template #default='scope'>
                      {{scope.row.stock}}（件）
                    </template>
                  </el-table-column>
                  <el-table-column label="原始价格（元）" prop="originalPrice">
                  </el-table-column>
                  <el-table-column label="售卖价格（元）" prop="price">
                  </el-table-column>
                  <el-table-column label="会员价格（元）" prop="vipPrice">
                  </el-table-column>
                  <el-table-column label="国际条码" prop="barCode">
                  </el-table-column>
                </el-table>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <el-table-column label="团购ID" prop="categoryId" align="center">
        </el-table-column>
        <el-table-column label="商品ID" prop="id" align="center">
        </el-table-column>
        <el-table-column label="商品名称" prop="title" align="center">
        </el-table-column>
        <el-table-column label="广告图片" prop="img" align="center">
          <template #default="scope">
            <el-popover placement="right" width="300" trigger="hover">
              <el-image style="width: 50px;" slot="reference" :src="scope.row.img"></el-image>
              <el-image style="width:100%;" :src="scope.row.img"></el-image>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="未满策略" align="center" prop="automaticRefund">
          <template slot-scope="scope">
            <el-tag :type="scope.row.automaticRefund == 0 ? 'success' : 'warning'">
              {{scope.row.automaticRefund == "0"? "发货": "退款"}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动状态" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status==0?'success':'primary'">
              {{scope.row.status == "0"? "冻结": "活动"}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gmtStart" label="开始时间" align="center">
          <template slot-scope="scope">
            {{new Date (scope.row.gmtStart).couponTime()}}
          </template>
        </el-table-column>
        <el-table-column prop="gmtEnd" label="结束时间" align="center">
          <template slot-scope="scope">
            {{new Date (scope.row.gmtEnd).couponTime()}}
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="当前人数" align="center">
        </el-table-column>
        <el-table-column prop="minNum" label="目标人数" align="center">
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope" v-if="scope.row.status=='0'">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 添加--编辑抽屉 -->
    <el-drawer :visible.sync="dialog" direction="ltr" custom-class="demo-drawer" ref="drawer" :show-close="false" :with-header="false" size="50%" :before-close="handleClose">
      <div class="box_drawer">
        <div>{{title+'团购商品'}}</div>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm" size="mini">取 消</el-button>
          <el-button type="primary" size="mini" @click="submitForm('ruleForm')">{{ title === '创建' ? '创 建' : '编辑' }}</el-button>
        </div>
      </div>
      <p>商品属性(spu)</p>
      <div class="box_form">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="138px" class="demo-ruleForm" :label-position="labelPosition">
          <el-form-item label="团购商品" prop="spuId">
            <el-cascader v-model="ruleForm.spuId" :options="commodity" :props="cmmodityParams" clearable placeholder="请选择团购商品" @change="changeParams"></el-cascader>
          </el-form-item>
          <el-form-item label="活动时间">
            <template>
              <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.gmtStart"></el-date-picker>
              至
              <el-date-picker type="date" placeholder="选择日期" v-model="ruleForm.gmtEnd"></el-date-picker>
            </template>
          </el-form-item>
          <el-form-item label="团购基础人数" prop="minNum">
            <el-input-number v-model="ruleForm.minNum" controls-position="right" @change="handleChange" :min="1"></el-input-number>
          </el-form-item>
          <el-form-item label="活动结束时人数没有达到基础人数采取">
            <el-radio-group v-model="ruleForm.automaticRefund" prop="automaticRefund">
              <el-radio-button :label="0">不退款我要发货</el-radio-button>
              <el-radio-button :label="1">自动退款我不发货</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="box_drawer">
        <div>商品类型(sku)</div>
        <div class="demo-drawer__footer">
          <el-popover placement="right" width="300" trigger="click" v-model="visible">
            <el-form>
              <el-form-item label="团购价格">
                <el-input-number v-model="groupPurchasePrice" controls-position="right" :min="1"></el-input-number>
                <span style="margin-left:5px">元</span>
              </el-form-item>
              <div style="text-align:right">
                <template>
                  <el-button size="mini" @click="visible = false">取消</el-button>
                  <el-button size="mini" type="primary" @click="groupPurchaseButton">确定</el-button>
                </template>
              </div>
            </el-form>
            <el-button slot="reference" type="primary" plain>批量定价</el-button>
          </el-popover>
        </div>
      </div>
      <!-- 表格 -->
      <el-table :data="initData" stripe style="width: 100%">
        <el-table-column prop="spuId" label="Skuld">
        </el-table-column>
        <el-table-column prop="barCode" label="SKu条形码">
        </el-table-column>
        <el-table-column prop="specification" label="类型名">
        </el-table-column>
        <el-table-column prop="stock" label="库存">
        </el-table-column>
        <el-table-column prop="price" label="现价/元">
        </el-table-column>
        <el-table-column prop="skuGroupShopPrice" label="团购价格/元">
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="Renovate(scope.row)">更新</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
    <!-- 更新弹框 -->
    <el-dialog title="更新团购价格" :visible.sync="dialogTableVisible" width="30%">
      <el-descriptions :column="1">
        <el-descriptions-item label="团购价格">
          <el-input-number v-model="group.gropPirce.skuGroupShopPrice" controls-position="right" :min="1" />
        </el-descriptions-item>
        <el-descriptions-item label="现价">{{group.gropPirce.price}}</el-descriptions-item>
        <el-descriptions-item label="sku类型名">{{group.gropPirce.title}}</el-descriptions-item>
      </el-descriptions>
      <div style="display: flex;justify-content: end;">
        <el-button @click="dialogTableVisible=false"> 取消</el-button>
        <el-button type="primary" @click="Makeprice">确定</el-button>
      </div>
    </el-dialog>
    <!-- 分页 --回到顶部 -->
    <div class="box_paging">
      <pagination :pageinfo="pageinfo" @change="changePage"></pagination>
    </div>
  </div>
</template>
<script>
import Pagination from "../../components/pagination/MyPagination.vue" //分页组件
import Apiadmin from "../../api/admin"
import { Message } from 'element-ui'
export default {
  components: {
    Pagination
  },
  data() {
    return {
      labelPosition: 'left',
      pageinfo: {
        limit: 10, //每页显示的数量
        page: 1,  //当前显示的页码
        total: 0, //数据总条数
        id: null,//团购商品的ID
        spuName: null, //团购商品的名称
        status: '', //团购商品的状态
      },
      tableData: [], //团购列表数据

      // 下拉框
      // 团购商品的状态
      adStatusMap: [{
        value: 0,
        name: '冻结'
      },
      {
        value: 1,
        name: '活动'
      }],
      title: '创建', //抽屉标题
      dialog: false, //抽屉显示或隐藏
      // loading: false,
      // 表单数据
      ruleForm: {
        spuId: '', // spuId
        gmtStart: '',//团购开始时间戳
        gmtEnd: '',//团购结束时间戳
        minNum: '',//	团购最低人数
        automaticRefund: 0,//团购人数未满是否自动退款
        groupShopSkuList: [],//团购sku链表
      },
      // 表单验证
      rules: {
        spuId: [
          { required: true, message: '请选择团购商品', trigger: 'blur' }
        ],
      },
      commodity: [], //团购商品数据
      cmmodityParams: { // 级联选择器的配置
        ocheckStrictly: true, // 父子节点不互相关联
        label: 'label',  //渲染上去的名字
        value: 'id', //选中时的id
        children: 'children',  //子节点数组
        emitPath: false // 只返回该节点的值
      },
      initData: [], //添加表格数据
      groupPurchasePrice: '',  //关联气泡框里面的数字选择器
      visible: false, //批量定价气泡关闭
      dialogTableVisible: false, //更新弹框隐藏显示
      group: {
        index: '',
        gropPirce: { //单独修改团购价格
          price: '',
          title: '',
          skuGroupShopPrice: '',

        }
      }

    }
  },
  created() {
    this.operateList()
  },
  methods: {
    // 请求团购管理数据
    operateList() {
      Apiadmin.groupshopList(this.pageinfo).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.tableData = res.data.items  //表格数据
          this.pageinfo.total = res.data.count  //分页总数据
        }
      })
      // 请求团购商品数据  
      Apiadmin.categoryTrees().then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.commodity = res.data
        }
      })
    },
    //团购商品改变事件，请求表格数据
    changeParams(id) {
      // console.log(id)
      Apiadmin.productList({ spuId: id }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.initData = res.data.skuList
          //添加时给skuList加skuId
          res.data.skuList.forEach(item => {
            item.skuId = item.id
          });
        }
      })
    },
    //查找团购管理用户
    onSeek() {
      this.pageinfo.page = 1, //查找页数重置为1
        // 请求数据时加载
        this.$showLoading(() => {
          this.operateList()
        })
    },
    // 抽屉取消按钮
    cancelForm() {
      // this.loading = false;
      this.dialog = false;
      clearTimeout(this.timer);
    },
    // 抽屉关闭提示信息
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    // 团购基础人数计数器事件
    handleChange(value) {
      // console.log(value);
    },
    // 添加
    addAdmin() {
      this.title = "创建"
      this.dialog = true
      this.initData = []  //清空表格数据
      this.initObj(this.ruleForm, {})   //清空表单
      this.groupPurchasePrice = ''; //清空气泡框内容
      // 解决添加出现验证提示之后关闭弹出框,点击编辑发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },
    //批量定价确认按钮
    groupPurchaseButton() {
      // 批量修改团购价格
      //给每个对象新加一个skuGroupShopPrice属性
      let arr = []
      this.initData.map((item, index) => {
        arr.push(Object.assign({}, item, { skuGroupShopPrice: this.groupPurchasePrice }))
      })
      if (!this.groupPurchasePrice) return Message.warning('团购价格不能为空!')
      if (this.initData.some(node => node.price < this.groupPurchasePrice)) return Message.error('团购价格不能高于现价')
      this.initData = arr //重新赋值
      this.visible = false //关闭气泡框
      this.groupPurchasePrice = ''; //清空气泡框内容

    },
    //  更新按钮
    Renovate(row) {
      // console.log(row)
      this.dialogTableVisible = true
      this.group.gropPirce = row
    },
    // 更新 单独修改团购价格 
    Makeprice() {
      let index = this.group.index
      if (this.group.gropPirce.skuGroupShopPrice > this.group.gropPirce.price) {
        this.$message({
          message: "团购价格不能高于现价!",
          type: 'error'
        });
      } else {
        this.$message({
          message: '更新成功',
          type: 'success'
        });
        this.dialogTableVisible = false   //弹窗关闭
      }
      this.initData[index].skuGroupShopPrice = this.group.gropPirce.skuGroupShopPrice
    },
    // 编辑
    handleEdit(row) {
      // console.log(row)
      this.title = "编辑"
      this.dialog = true
      this.initData = row.groupShopSkuDTOList
      this.ruleForm = JSON.parse(JSON.stringify(row))
      // 解决编辑出现验证提示之后关闭弹出框,点击添加发现验证信息还存在
      this.$nextTick(() => {
        this.resetForm("ruleForm")
      })
    },

    //创建 --编辑提交按钮
    submitForm(formName) {
      if (!this.ruleForm.gmtStart) return Message.warning('请选择开始时间!')
      if (!this.ruleForm.gmtEnd) return Message.warning('请选择结束时间!')
      if (this.ruleForm.gmtStart > this.ruleForm.gmtEnd) return Message.warning('开始时间要低于结束时间!')
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.groupShopSkuList = JSON.stringify(this.initData)
          //将开始时间和结束时间转换成时间戳
          this.ruleForm.gmtStart = new Date(this.ruleForm.gmtStart).getTime()
          this.ruleForm.gmtEnd = new Date(this.ruleForm.gmtEnd).getTime()
          // 添加
          if (this.title == "创建") {
            Apiadmin.groupshopAdd(this.ruleForm).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.dialog = false //抽屉关闭
                this.operateList() //刷新页面
                this.ruleForm = {} //清空表单
                this.$message({
                  message: '创建成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "创建失败",
                  type: 'error'
                });
              }
            })
          }
          // 修改
          if (this.title == "编辑") {
            Apiadmin.groupshopEdit(this.ruleForm).then(res => {
              // console.log(res)
              if (res.errno == 200) {
                this.dialog = false //抽屉关闭
                this.operateList() //刷新页面
                this.ruleForm = {} //清空表单
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: "修改失败",
                  type: 'error'
                });
              }
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    // 删除
    handleDelete(row) {
      // console.log(row)
      Apiadmin.groupshopDelete({ id: row.id }).then(res => {
        // console.log(res)
        if (res.errno == 200) {
          this.$confirm('此操作将永久删除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(res => {
            this.operateList()   //刷新页面
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }).catch(err => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          })
        }
      })
    },
    //去除表单验证
    resetForm(formName) {
      //clearValidate方法为移除表单的校验结果          
      this.$refs[formName].clearValidate();
    },
    // 子传过来的方法和页长跟当前页
    changePage(e) {
      // console.log(e)
      this.pageinfo = JSON.parse(JSON.stringify(e))
      this.$nextTick(() => {
        this.operateList()
      })
    },
  }
}
</script>
<style scoped  lang="less">
.box_input {
  .el-input {
    width: 15%;
  }
}
// 弹框样式
.box_drawer {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid #cccccc;
  line-height: 80px;
  padding: 0 20px;
}
p {
  padding: 0 20px;
}
.box_form {
  display: flex;
  justify-content: center;
  border-bottom: 1px solid #cccccc;
}
</style>